<?php

/* @var $this yii\web\View */

/* @var $id integer */

use yii\helpers\Url;

$this->title = Yii::t('app', $id ? 'Update Product' : 'Create Product');
$this->params['breadcrumbs'][] = $this->title;
?>
<div id="app">
</div>
<? $this->beginBlock('otherJs') ?>
<?= $this->render('/jstemplate/validate') ?>
<?= $this->render('/jstemplate/left_drawer') ?>
<?= $this->render('/jstemplate/search_form') ?>
<?= $this->render('/jstemplate/notify') ?>
<script type="text/x-template" id="app-template">
    <v-app>
        <notify></notify>
        <left-drawer ref="left_drawer"></left-drawer>

        <v-main class="grey lighten-3">
            <v-app-bar
                    elevation="0"
                    color="primary"
                    dark
                    app
            >
                <v-toolbar-title><?= $this->title ?></v-toolbar-title>
                <v-spacer></v-spacer>

                <v-app-bar-nav-icon @click="openDrawer"></v-app-bar-nav-icon>

            </v-app-bar>
            <v-container>
                <validation-observer
                        ref="observer"
                        v-slot="{ invalid,validated,handleSubmit,validate }"
                >
                    <form @submit.prevent="handleSubmit(createItem)">
                        <v-card :loading="loading" flat>
                            <v-subheader>
                                基础信息
                            </v-subheader>
                            <v-divider></v-divider>
                            <v-card-text>
                                <v-container>

                                    <validation-provider
                                            v-slot="{ errors,valid }"
                                            name="<?= Yii::t('app', 'Title') ?>"
                                            rules="required"
                                    >
                                        <v-text-field
                                                v-model="handForm.title"
                                                label="<?= Yii::t('app', 'Title') ?>"
                                                :error-messages="errors"
                                                :success="valid"
                                                class="m-3"
                                        ></v-text-field>
                                    </validation-provider>
                                    <validation-provider
                                            v-slot="{ errors,valid }"
                                            name="<?= Yii::t('app', 'Description') ?>"
                                            rules="required"
                                    >
                                        <v-text-field
                                                v-model="handForm.description"
                                                label="<?= Yii::t('app', 'Description') ?>"
                                                :error-messages="errors"
                                                :success="valid"
                                                class="m-3"
                                        ></v-text-field>
                                    </validation-provider>
                                    <validation-provider
                                            v-slot="{ errors,valid }"
                                            name="<?= Yii::t('app', 'Price') ?>"
                                            rules="required"
                                    >
                                        <v-text-field
                                                v-model="handForm.price"
                                                label="<?= Yii::t('app', 'Price') ?>"
                                                type="number"
                                                prefix="¥"
                                                :error-messages="errors"
                                                :success="valid"
                                                class="m-3"
                                        ></v-text-field>
                                    </validation-provider>
                                    <validation-provider
                                            v-slot="{ errors,valid }"
                                            name="<?= Yii::t('app', 'Stock Num') ?>"
                                            rules="required"
                                    >
                                        <v-text-field
                                                v-model="handForm.stock_num"
                                                label="<?= Yii::t('app', 'Stock Num') ?>"
                                                type="number"
                                                :error-messages="errors"
                                                :success="valid"
                                                class="m-3"
                                        ></v-text-field>
                                    </validation-provider>
                                    <v-file-input
                                            accept="image/*"
                                            label="选择图片"
                                            chips
                                            @change="changeFile"
                                            class="m-3"
                                    ></v-file-input>
                                    <v-img v-if="handForm.pic_url != ''"
                                           :src="'<?= Url::to('@upload') ?>\\'+handForm.pic_url" max-width="150">
                                    </v-img>

                                </v-container>
                            </v-card-text>
                        </v-card>
                        <v-card :loading="loading" flat class="mt-3">
                            <v-subheader>
                                属性
                            </v-subheader>
                            <v-divider></v-divider>
                            <v-card-text>
                                <v-subheader>
                                    分类
                                </v-subheader>

                                <validation-provider
                                        v-slot="{ errors,valid }"
                                        name="<?= Yii::t('app', 'Classify Id') ?>"
                                        rules="required"
                                >
                                    <v-select
                                            v-model="handForm.classify_id"
                                            :items="configs.classifies"
                                            item-text="name"
                                            item-value="id"
                                            label="<?= Yii::t('app', 'Classify Id') ?>"
                                            :error-messages="errors"
                                            :success="valid"
                                            class="m-3"
                                    >

                                    </v-select>
                                </validation-provider>
                                <v-subheader>
                                    选项
                                </v-subheader>
                                <v-treeview
                                        v-model="handForm.select_values"
                                        :items="configs.attr_names"
                                        :value="handForm.origin_select_values"
                                        selectable
                                        item-key="id"
                                        item-text="name"
                                        item-children="attrValues"
                                        open-all
                                        color="primary"
                                        class="mt-3"
                                ></v-treeview>
                            </v-card-text>
                        </v-card>

                        <v-card :loading="loading" flat class="mt-3">
                            <v-subheader>
                                SKU
                            </v-subheader>
                            <v-divider></v-divider>
                            <v-card-text>
                                <v-data-table
                                        :headers="handForm.sku_headers"
                                        :items="handForm.sku_desserts"
                                        :items-per-page="-1"
                                >
                                    <template v-slot:item.actions="{ item }">
                                        <v-btn
                                                color="primary"
                                                outlined
                                                small
                                                @click="onUpdateSku(item)"
                                        >
                                            编辑
                                        </v-btn>
                                    </template>
                                </v-data-table>
                            </v-card-text>
                        </v-card>

                        <v-footer app>
                            <v-container class="d-flex justify-center">
                                <v-btn
                                        color="primary"
                                        :loading="loading"
                                        block
                                        :disabled="invalid || !validated"
                                        type="submit"
                                >
                                    提交
                                </v-btn>
                            </v-container>
                        </v-footer>
                    </form>
                </validation-observer>
            </v-container>
        </v-main>
        <v-dialog v-model="editSkuDialog" max-width="290">
            <v-card>
                <v-card-title class="headline">
                    {{ change_label}}
                </v-card-title>
                <v-card-text>

                    <v-text-field
                            v-model="editSkuForm.price"
                            label="<?= Yii::t('app', 'Price') ?>"
                    ></v-text-field>
                    <v-text-field
                            v-model="editSkuForm.stock_num"
                            label="<?= Yii::t('app', 'Stock Num') ?>"
                    ></v-text-field>
                </v-card-text>
                <v-card-actions>
                    <v-spacer></v-spacer>
                    <v-btn
                            color="primary"
                            text
                            @click="updateSku"
                    >
                        提交
                    </v-btn>
                    <v-btn
                            color="grey"
                            text
                            @click="editSkuDialog = false"
                    >
                        取消
                    </v-btn>
                </v-card-actions>
            </v-card>
        </v-dialog>
        <v-snackbar
                v-model="snackbarOpen"
        >
            {{ snackbarText }}

            <template v-slot:action="{ attrs }">
                <v-btn
                        color="blue"
                        text
                        v-bind="attrs"
                        @click="snackbarOpen = false"
                >
                    Close
                </v-btn>
            </template>
        </v-snackbar>
    </v-app>
</script>
<script>
    new Vue({
        el: '#app',
        vuetify: vuetify,
        data: function () {
            return {
                loading: false,
                snackbarOpen: false,
                snackbarText: '',
                isCreate: false,
                editSkuIndex: 0,
                editSkuDialog: false,
                editSkuForm: {
                    price: 0,
                    stock_num: 0
                },
                configs: {
                    classifies: [],
                    attr_names: []
                },
                handForm: {
                    id: <?=$id?>,
                    title: '',
                    description: '',
                    price: 0,
                    stock_num: 0,
                    classify_id: 0,
                    pic_url: '',
                    select_values: [],
                    origin_select_values: [],
                    sku_headers: [],
                    sku_desserts: []
                }
            }
        },
        watch: {
            options: {
                handler() {
                    this.getDataFromApi()
                },
                deep: true,
            },
            'handForm.classify_id': function (newVal, oldVal) {
                let vue = this
                http.get("attr-names", {
                    params: {
                        page: -1,
                        expand: 'attrValues',
                        filter: {
                            classify_id: {'eq': newVal}
                        }
                    },
                    paramsSerializer: function (params) {
                        return Qs.stringify(params, {arrayFormat: 'indices'})
                    },
                }).then(function (response) {
                    let ret = response.data;
                    vue.configs.attr_names = ret;
                    vue.$nextTick(() => {
                        vue.handForm.select_values = vue.handForm.origin_select_values;
                    })
                })
            },
            'handForm.select_values': function (newVal, oldVal) {
                console.log(newVal);
                let vue = this;
                http.post("sku/compute", http.param({
                    attr_value_ids: newVal,
                    product_id: <?=$id?>
                })).then(function (response) {
                    console.log(response)
                    vue.handForm.sku_headers = response.data.headers;
                    vue.handForm.sku_desserts = response.data.desserts;
                })
            }
        },
        computed: {
            change_label: function () {
                if (this.handForm.id == 0) {
                    return '<?=Yii::t('app', 'Create Product')?>'
                } else {
                    return '<?=Yii::t('app', 'Update Product')?>';
                }
            }
        },
        mounted() {
            let vue = this

            http.get("classifies", {
                params: {
                    page: -1,
                    expand: '',
                    filter: {}
                },
                paramsSerializer: function (params) {
                    return Qs.stringify(params, {arrayFormat: 'indices'})
                },
            }).then(function (response) {
                vue.configs.classifies = response.data;
            });

            if (vue.handForm.id != 0) {
                http.get("products/" + vue.handForm.id, {
                    params: {
                        expand: 'attrValueIds'
                    }
                }).then(function (response) {
                    let ret = response.data;
                    vue.handForm.title = ret.title;
                    vue.handForm.description = ret.description;
                    vue.handForm.price = ret.price;
                    vue.handForm.stock_num = ret.stock_num;
                    vue.handForm.classify_id = ret.classify_id;
                    vue.handForm.pic_url = ret.pic_url;
                    vue.handForm.origin_select_values = ret.attrValueIds
                    vue.$nextTick(() => {
                        vue.$refs.observer.validate()
                    });
                    vue.loading = false;
                });
            }
        },
        methods: {
            createItem() {
                let vue = this;
                console.log(111);
                if (vue.handForm.id === 0) {
                    http.post("products", http.param(vue.handForm)).then(function (response) {
                        vue.changeResult('<?=Yii::t('app', 'Create Success')?>')
                    }).catch(vue.handleError)
                } else {
                    http.patch("products/" + vue.handForm.id, http.param(vue.handForm)).then(function (response) {
                        vue.changeResult('<?=Yii::t('app', 'Update Success')?>')
                    }).catch(vue.handleError)
                }
            },
            changeFile(file) {
                let vue = this;
                const suffix = file.name.split('.')
                const ext = suffix.splice(suffix.length - 1, 1)[0]
                if (window.FileReader) {
                    let reader = new FileReader();
                    reader.onload = function (e) {
                        console.log(e.target.result);
                        http.post("picture/upload", http.param({
                            pic_data: e.target.result,
                            ext: ext
                        })).then(function (response) {
                            let ret = response.data;
                            vue.handForm.pic_url = ret.pic_url
                            console.log(ret);
                        })
                    }
                    reader.readAsDataURL(file)
                }
            },
            changeResult(msg) {
                this.snackbarText = msg;
                this.snackbarOpen = true;

                window.location.href = '<?=Url::to('index')?>'
            },
            onUpdateSku(item) {
                this.editSkuIndex = this.handForm.sku_desserts.indexOf(item)
                this.editSkuForm.price = item.price;
                this.editSkuForm.stock_num = item.stock_num;
                this.editSkuDialog = true;
            },
            updateSku(){
                this.handForm.sku_desserts[this.editSkuIndex].price = this.editSkuForm.price;
                this.handForm.sku_desserts[this.editSkuIndex].stock_num = this.editSkuForm.stock_num;
                this.editSkuDialog = false;
            },
            handleError(error) {
                if (error.response.status == 422) {
                    console.log(error.response);
                    this.snackbarText = error.response.data[0].message;
                    this.snackbarOpen = true;
                }
                return Promise.reject(error);
            },
            openDrawer() {
                this.$refs.left_drawer.toggleLeftDrawerVisible()
            },
        },
        template: '#app-template'
    })
</script>
<?= $this->endBlock() ?>
